package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.RoleDAO;
import com.hanoi.wiki.dao.UserDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.exception.FunctionalException;
import com.hanoi.wiki.manager.RoleManager;
import com.hanoi.wiki.model.Role;
import com.hanoi.wiki.model.User;
import com.hanoi.wiki.model.json.RoleJson;

@Component
@Transactional
public class RoleManagerImpl extends BaseManagerImpl implements RoleManager{

	@Autowired
	private RoleDAO roleDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	public int save(RoleJson json) throws FunctionalException {
		try{	
			Role role = new Role(json);
			
			List<User> users = new ArrayList<User>();
			User user;
			for(Integer i : json.getUsers()) {
				user = userDAO.get(i);
				if(user != null) {
					users.add(user);
				}
			}
			
			role.setUsers(users);
			
			return roleDAO.saveRole(role);
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return 0;
	}

	public List<RoleJson> getList() throws FunctionalException {
		List<RoleJson> roleJsons = new ArrayList<RoleJson>();
		List<Role> roles = roleDAO.getList();
		try {
			for(Role role : roles) {
				roleJsons.add(new RoleJson(role));
			}
		} catch(DataAccessException e) {
			log.error("", e);
		}
		
		return roleJsons;
	}

	public RoleJson get(Integer id) throws FunctionalException {
		try {
			return new RoleJson(roleDAO.get(id));
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return null;
	}

	public void remove(Integer id) throws FunctionalException {
		try {
			if(roleDAO.get(id) != null) {
				roleDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
		
	}

	public void update(RoleJson json) throws FunctionalException {
		try{	
			Role role = new Role(json);
			
			List<User> users = new ArrayList<User>();
			User user;
			for(Integer i : json.getUsers()) {
				user = userDAO.get(i);
				if(user != null) {
					users.add(user);
				}
			}
			
			role.setUsers(users);
			role.setId(json.getId());
			
			roleDAO.update(role);
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}
	
}
